import React, { useCallback, useContext, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  StatusBar,
  TouchableOpacity,
  ActivityIndicator,
  Alert,
} from "react-native";
import { useDispatch } from "react-redux";
import { FlatList } from "react-native-gesture-handler";
import SearchBar from "../../components/SearchBar";
import FilterModal from "../../components/FilterModal";
import Dropdown from "../../components/dropdown";
import MaterialCard from "../../components/materialCard";
import GoodsCard from "../../components/GoodsCard";
import ComMaterialContext from "../../context/suppiler/comMaterialContext";
import GoodsContext from "../../context/suppiler/goodsContext";
import MaterialContext from "../../context/suppiler/materialContext";
import { signout } from "../../store/actions";

const Separator = () => <View style={styles.itemSeparator} />;

const SupplierHome = ({ navigation }) => {
  const dispatch = useDispatch();
  const {
    comMaterial,
    isComMatError,
    isComMatLoading,
    filterComMaterial,
    resetComMaterial,
  } = useContext(ComMaterialContext);
  const { Goods, isGoodsError, isGoodsLoading, filterGoods, resetGoods } =
    useContext(GoodsContext);
  const { material, isMaterialError, isMaterialLoading } =
    useContext(MaterialContext);
  const [materialFilter, setMaterialFilter] = useState([]);
  const [goodsFilter, setGoodsFilter] = useState([]);

  const types = ["商品", "材料"];
  const [type, setTypes] = useState(0);

  let result = [];
  // console.log("首页商品---", Goods);

  if (!isMaterialLoading) {
    const categories = material.map((item) => {
      return item.category;
    });

    for (let j = 0; j < categories.length; j++) {
      let detail = material[j].types.map((item) => {
        return item.type;
      });

      result.push({
        category: categories[j],
        types: detail,
      });
    }
  }

  const onMaterialSave = (data) => {
    setMaterialFilter(data);

    filterComMaterial(result, data);
  };

  const onGoodsSave = (data) => {
    setGoodsFilter(data);
    filterGoods(result, data);
  };

  const onDelete = useCallback((index) => {
    console.log("删除商品index为---", index);
  }, []);

  const [isMutilDelete, setIsMUtilDelete] = useState(false);
  const MultiDelte = () => {
    setIsMUtilDelete(true);
    // console.log("初始数组", selectedItem);
  };
  // const materialList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  const [selectedItem, setSelectedItem] = useState([null]);
  const onPressSelect = (index, ifCancel) => {
    // console.log("选择了---", index + 1);
    // console.log("是否为空", ifCancel);
    let list = selectedItem;
    if (ifCancel) {
      list[index + 1] = null;
    } else {
      list[index + 1] = index + 1;
    }
    setSelectedItem(list);
    // console.log("当前数组", selectedItem);
    let i = selectedItem.filter((v) => v);
    // console.log("过滤后数组", i);
  };

  const confirmMultiDelete = () => {
    Alert.alert("提示", "确定要删除已选内容吗?", [
      {
        text: "取消",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          setIsMUtilDelete(false);
        },
      },
    ]);
  };
  return (
    <View style={styles.page}>
      <View style={styles.container}>
        <SearchBar
          onPressHome={() => navigation.navigate("SuppilerUser")}
          onPressSearch={() => navigation.navigate("SearchScreen")}
          onPressAddMaterial={() => navigation.navigate("MaterialAdd")}
          onPressAddGood={() =>
            navigation.navigate("SuppilerAdd", {
              title: "添加商品",
              type: "add",
            })
          }
          onPressBack={() => {
            dispatch(signout());
          }}
          onPressMultiDelete={MultiDelte}
        />
        <View style={styles.tagView}>
          <Dropdown
            ifFirst={1}
            initialValues={{
              initKey: type,
              initOptions: types,
            }}
            initialStyles={{
              valueWith: 60,
              valueMarginTop: 0,
              optionsWidth: 70,
              optionsBackGroundColor: "#eee",
              optionsBorderColor: "#ccc",
            }}
            onSelect={(item, value) => {
              setTypes(value);
              if (value === 0) {
                resetComMaterial();
              } else {
                resetGoods();
              }
            }}
          />

          {type === 0 && (
            <FilterModal tagList={result} onSave={onGoodsSave} type={2} />
          )}
          {type === 1 && (
            <FilterModal tagList={result} onSave={onMaterialSave} type={1} />
          )}
        </View>
        <View style={styles.list}>
          {type === 0 ? (
            <FlatList
              data={Goods}
              renderItem={({ item, index }) => {
                return (
                  <GoodsCard
                    key={index}
                    index={index}
                    isMutilDelete={isMutilDelete}
                    onPressSelect={onPressSelect}
                    onDelete={onDelete}
                    showData={item}
                    onQuery={() => {
                      navigation.navigate("SuppilerAdd", {
                        itemDetail: item,
                        title: "编辑商品",
                        type: "edit",
                      });
                    }}
                  />
                );
              }}
              // ItemSeparatorComponent={() => <Separator />}
              keyExtractor={(item, index) => index.toString()}
              ListEmptyComponent={() => (
                <Text
                  style={{
                    fontSize: 16,
                    alignSelf: "center",
                    color: "#B3B3B3",
                  }}
                >
                  你还没发布任何商品
                </Text>
              )}
            />
          ) : (
            <FlatList
              data={comMaterial}
              renderItem={({ item, index }) => {
                return (
                  <MaterialCard
                    key={index}
                    index={index}
                    item={item}
                    isMutilDelete={isMutilDelete}
                    onPressSelect={onPressSelect}
                  />
                );
              }}
              keyExtractor={(item, index) => index.toString()}
              ListEmptyComponent={() => (
                <Text
                  style={{
                    fontSize: 16,
                    alignSelf: "center",
                    color: "#B3B3B3",
                  }}
                >
                  你还没发布任何材料
                </Text>
              )}
            />
          )}
        </View>

        {isMutilDelete && (
          <View style={styles.buttonOptions}>
            <TouchableOpacity
              style={styles.cancel}
              onPress={() => {
                setIsMUtilDelete(false);
              }}
            >
              <Text style={styles.cancelText}>取消</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.confirm}
              onPress={() => {
                confirmMultiDelete();
              }}
            >
              <Text style={styles.confirmText}>确定</Text>
            </TouchableOpacity>
          </View>
        )}
      </View>
      {(isComMatLoading || isGoodsLoading || isMaterialLoading) && (
        <View>
          <View
            style={{
              position: "absolute",
              width: "100%",
              height: "100%",
              zIndex: 2,
              backgroundColor: "#727272",
              opacity: 0.12,
            }}
          ></View>
          <View
            style={{
              width: "100%",
              height: "100%",
              zIndex: 5,
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <ActivityIndicator color="#2E9AFE" size="large" />
          </View>
        </View>
      )}

      {(isGoodsError || isComMatError || isMaterialError) && (
        <View>
          <View
            style={{
              position: "absolute",
              width: "100%",
              height: "100%",
              zIndex: 2,
              backgroundColor: "#727272",
              opacity: 0.2,
            }}
          ></View>
          <View
            style={{
              width: "100%",
              height: "100%",
              zIndex: 5,
            }}
          >
            <Text
              style={{
                fontSize: 17,
                alignSelf: "center",
                top: "50%",
                color: "#525252",
                fontWeight: "bold",
              }}
            >
              网络开小差了...
            </Text>
          </View>
        </View>
      )}

      {/* <Text>选择了:</Text>
      {Filter.length === 0 ? (
        <Text>暂无选择</Text>
      ) : (
        Filter.map((tag, index) => {
          return <Text key={index}>{tag}</Text>;
        })
      )} */}
    </View>
  );
};

const styles = StyleSheet.create({
  page: {
    flex: 1,
    marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    flexDirection: "column",
    backgroundColor: "#fff",
    backgroundColor: "#FAFAFA",
  },
  container: {
    flex: 1,
  },
  tagView: {
    // marginTop: 5,
    flexDirection: "row",
    padding: 5,
    paddingRight: 10,
    paddingLeft: 10,
    alignItems: "center",
    justifyContent: "space-between",
    backgroundColor: "#F2F2F2",
  },
  list: {
    // backgroundColor: "yellow",
    flex: 1,
    marginTop: 20,
    marginBottom: 10,
  },
  material: {
    flexDirection: "row",
    justifyContent: "space-between",
  },
  buttonOptions: {
    flexDirection: "row",
    justifyContent: "center",
    alignContent: "center",
    padding: 15,
    marginBottom: 5,
  },
  cancel: {
    flex: 3,
    padding: 10,
    marginRight: 20,
    borderWidth: 1.5,
    borderColor: "#F9be7d",

    alignItems: "center",
    justifyContent: "center",
    borderRadius: 5,
  },
  confirm: {
    borderRadius: 5,
    flex: 7,
    padding: 10,
    backgroundColor: "#F9be7d",
    alignItems: "center",
    justifyContent: "center",
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  cancelText: {
    fontSize: 16,
    color: "#22254c",
  },
  confirmText: {
    fontSize: 16,
    color: "#fff",
    fontWeight: "bold",
  },
  itemSeparator: {
    backgroundColor: "#e4e4e4",
    height: 1,
    width: "90%",
    alignSelf: "center",
  },
});

export default SupplierHome;
